package cn.iocoder.yudao.module.mqtt.service.mqtt;

import cn.iocoder.yudao.module.mqtt.dal.dataobject.config.MqttConfig2DO;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.mqtt.dal.mysql.config.MqttConfig2Mapper;
import cn.iocoder.yudao.module.mqtt.dal.mysql.device.DeviceMapper;
import cn.iocoder.yudao.module.mqtt.framework.config.MqttReconnectProperties;
import cn.iocoder.yudao.module.mqtt.framework.mqtt.MqttInstanceManager;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * MQTT连接监控服务
 * 定期检查连接状态，发现断开时自动重连
 *
 * @author 芋道源码
 */
@Slf4j
@Service
public class MqttConnectionMonitorService {

    @Autowired
    private MqttInstanceManager mqttInstanceManager;
    @Autowired
    private MqttConfigService mqttConfigService;
    @Autowired
    private MqttReconnectProperties reconnectProperties;

    @Resource
    private DeviceMapper deviceMapper;

    @Autowired
    private MqttConfig2Mapper config2Mapper;

    public void myCheckConnectionStatus() {
        if (!reconnectProperties.isMonitorEnabled()) {
            return;
        }
        try {
            Set<Long> runningInstanceIds = mqttInstanceManager.getRunningInstanceIds();
            for (Long configId : runningInstanceIds) {
                boolean isConnect = mqttInstanceManager.pingClient(configId);
                MqttConfig2DO updateObj = new MqttConfig2DO();
                if(!isConnect){
                    log.info("与服务器断开");
                    updateObj.setIsOnline("0");//离线
                }else{
                    updateObj.setIsOnline("1");//离线
                }
                updateObj.setId(configId);
                config2Mapper.updateById(updateObj);


                DeviceDO ddo = new DeviceDO();
                ddo.setIsOnline(updateObj.getIsOnline());
                deviceMapper.update(ddo,
                        new QueryWrapper<DeviceDO>().eq("mqtt_config_id",configId));

                System.out.println(1);
            }
        } catch (Exception e) {
            log.error("MQTT连接监控过程中发生异常", e);
        }
    }

    public void checkConnectionStatus() {
        if (!reconnectProperties.isMonitorEnabled()) {
            return;
        }
        try {
            Set<Long> runningInstanceIds = mqttInstanceManager.getRunningInstanceIds();
            
            for (Long configId : runningInstanceIds) {
                try {
                    // 检查连接状态
                    boolean isConnected = mqttInstanceManager.isInstanceConnected(configId);
                    boolean isReconnecting = mqttInstanceManager.isReconnecting(configId);
                    
                    if (!isConnected && !isReconnecting) {
                        log.warn("检测到MQTT实例连接断开，开始重连，配置ID: {}", configId);
                        
                        // 记录详细的连接断开信息
                        log.error("=== 监控检测到MQTT连接断开 ===");
                        log.error("配置ID: {}", configId);
                        log.error("检测时间: {}", java.time.LocalDateTime.now());
                        log.error("检测方式: 定时监控检查");
                        log.error("连接状态: 未连接");
                        log.error("重连状态: 未重连中");
                        log.error("===============================");
                        
                        // 检查配置是否仍然启用
                        var config = mqttConfigService.getConfigById(configId);
                        if (config != null && config.getEnabled()) {
                            mqttInstanceManager.reconnectInstance(configId);
                        } else {
                            log.info("MQTT配置已禁用，跳过重连，配置ID: {}", configId);
                        }
                    } else if (isConnected) {
                        log.debug("MQTT实例连接正常，配置ID: {}", configId);
                    } else if (isReconnecting) {
                        log.debug("MQTT实例正在重连中，配置ID: {}", configId);
                    }
                    
                } catch (Exception e) {
                    log.error("检查MQTT实例连接状态时发生异常，配置ID: {}", configId, e);
                }
            }
        } catch (Exception e) {
            log.error("MQTT连接监控过程中发生异常", e);
        }
    }

    /**
     * 手动触发连接检查
     */
    public void manualCheckConnection() {
        log.info("手动触发MQTT连接状态检查");
        checkConnectionStatus();
    }

    /**
     * 获取连接状态报告
     */
    public String getConnectionStatusReport() {
        StringBuilder report = new StringBuilder();
        report.append("MQTT连接状态报告:\n");
        
        Set<Long> runningInstanceIds = mqttInstanceManager.getRunningInstanceIds();
        
        if (runningInstanceIds.isEmpty()) {
            report.append("  没有运行的MQTT实例\n");
        } else {
            for (Long configId : runningInstanceIds) {
                try {
                    boolean isConnected = mqttInstanceManager.isInstanceConnected(configId);
                    boolean isReconnecting = mqttInstanceManager.isReconnecting(configId);
                    
                    report.append(String.format("  配置ID: %d, 连接状态: %s, 重连状态: %s\n", 
                            configId, 
                            isConnected ? "已连接" : "未连接",
                            isReconnecting ? "重连中" : "正常"));
                    
                } catch (Exception e) {
                    report.append(String.format("  配置ID: %d, 状态检查失败: %s\n", configId, e.getMessage()));
                }
            }
        }
        
        return report.toString();
    }
} 